package com.ruoyi.web.util;
import org.apache.commons.lang3.StringUtils;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUrlConnectionToInterface {
    /**
     * 以post或get方式调用对方接口方法，
     * @param pathUrl
     */
    public static String doPostOrGet(String pathUrl, String data){
        OutputStreamWriter out = null;
        BufferedReader br = null;
        String result = "";
        String[] user_agent_array = {
                "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
                "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
                "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0",
                "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; InfoPath.3; rv:11.0) like Gecko",
                "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)",
                "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)",
                "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)",
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
                "Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
                "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11",
                "Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11",
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
                "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon 2.0)",
                "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; TencentTraveler 4.0)",
                "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",
                "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; The World)",
                "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SE 2.X MetaSr 1.0; SE 2.X MetaSr 1.0; .NET CLR 2.0.50727; SE 2.X MetaSr 1.0)",
                "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)",
                "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Avant Browser)",
                "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",
                "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
                "Mozilla/5.0 (iPod; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
                "Mozilla/5.0 (iPad; U; CPU OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
                "Mozilla/5.0 (Linux; U; Android 2.3.7; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
                "MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22; CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
                "Opera/9.80 (Android 2.3.4; Linux; Opera Mobi/build-1107180945; U; en-GB) Presto/2.8.149 Version/11.10",
                "Mozilla/5.0 (Linux; U; Android 3.0; en-us; Xoom Build/HRI39) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13",
                "Mozilla/5.0 (BlackBerry; U; BlackBerry 9800; en) AppleWebKit/534.1+ (KHTML, like Gecko) Version/6.0.0.337 Mobile Safari/534.1+",
                "Mozilla/5.0 (hp-tablet; Linux; hpwOS/3.0.0; U; en-US) AppleWebKit/534.6 (KHTML, like Gecko) wOSBrowser/233.70 Safari/534.6 TouchPad/1.0",
                "Mozilla/5.0 (SymbianOS/9.4; Series60/5.0 NokiaN97-1/20.0.019; Profile/MIDP-2.1 Configuration/CLDC-1.1) AppleWebKit/525 (KHTML, like Gecko) BrowserNG/7.1.18124",
                "Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0; HTC; Titan)",
                "UCWEB7.0.2.37/28/999",
                "NOKIA5700/ UCWEB7.0.2.37/28/999",
                "Openwave/ UCWEB7.0.2.37/28/999",
                "Mozilla/4.0 (compatible; MSIE 6.0; ) Opera/UCWEB7.0.2.37/28/999",
                "Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25",
        };
        String user_agent = StringUtils.join(user_agent_array, ";");



        try {
            URL url = new URL(pathUrl);
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //请求方式
            conn.setRequestMethod("POST");
            //conn.setRequestMethod("GET");
            conn.setRequestProperty("contentType", "UTF-8");

            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", user_agent);
            //conn.setRequestProperty("Content-Type", "application/json;charset=GBK");
            //DoOutput设置是否向httpUrlConnection输出，DoInput设置是否从httpUrlConnection读入，此外发送post请求必须设置这两个
            conn.setDoOutput(true);
            conn.setDoInput(true);
            /**
             * 下面的三句代码，就是调用第三方http接口
             */
            //获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            //发送请求参数即数据
            out.write(data);
            //flush输出流的缓冲
            out.flush();
            /**
             * 下面的代码相当于，获取调用第三方http接口后返回的结果
             */

            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
            String str = "";
            while ((str = br.readLine()) != null){
                result += str;
            }
            System.out.println(result);

            //关闭流
            is.close();
            //断开连接，disconnect是在底层tcp socket链接空闲时才切断，如果正在被其他线程使用就不切断。
            conn.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (out != null){
                    out.close();
                }
                if (br != null){
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    public static void main(String[] args ) {
        httpURLPOSTCase("http://127.0.0.1:4428/api/queryPeQuestionnaire/saveHealthNaire", "{\"userId\":\"TJ02518811\",\"answerJson\":\"%5B%7B%22questionnaireId%22:%220007%22,%22questionCode%22:%220001%22,%22questionType%22:%223%22,%22pid%22:%22-1%22,%22answerCode%22:%22,0001%22,%22answerContext%22:%22%22%7D,%7B%22questionnaireId%22:%220007%22,%22questionCode%22:%220002%22,%22questionType%22:%223%22,%22pid%22:%22-1%22,%22answerCode%22:%22,0001%22,%22answerContext%22:%22%22%7D,%7B%22questionnaireId%22:%220007%22,%22questionCode%22:%220003%22,%22questionType%22:%223%22,%22pid%22:%22-1%22,%22answerCode%22:%22,0001%22,%22answerContext%22:%22%22%7D,%7B%22questionnaireId%22:%220007%22,%22questionCode%22:%220004%22,%22questionType%22:%223%22,%22pid%22:%22-1%22,%22answerCode%22:%22,0001%22,%22answerContext%22:%22%22%7D,%7B%22questionnaireId%22:%220007%22,%22questionCode%22:%220005%22,%22questionType%22:%222%22,%22pid%22:%22-1%22,%22answerCode%22:%220001%22,%22answerContext%22:%22%22%7D,%7B%22questionnaireId%22:%220007%22,%22questionCode%22:%220006%22,%22questionType%22:%222%22,%22pid%22:%22-1%22,%22answerCode%22:%220001%22,%22answerContext%22:%22%22%7D,%7B%22questionnaireId%22:%220007%22,%22questionCode%22:%220007%22,%22questionType%22:%223%22,%22pid%22:%22-1%22,%22answerCode%22:%22,0001%22,%22answerContext%22:%22%22%7D,%7B%22questionnaireId%22:%220007%22,%22questionCode%22:%220008%22,%22questionType%22:%222%22,%22pid%22:%22-1%22,%22answerCode%22:%220001%22,%22answerContext%22:%22%22%7D,%7B%22questionnaireId%22:%220007%22,%22questionCode%22:%220009%22,%22questionType%22:%222%22,%22pid%22:%22-1%22,%22answerCode%22:%220001%22,%22answerContext%22:%22%22%7D,%7B%22questionnaireId%22:%220007%22,%22questionCode%22:%220010%22,%22questionType%22:%222%22,%22pid%22:%22-1%22,%22answerCode%22:%220001%22,%22answerContext%22:%22%22%7D,%7B%22questionnaireId%22:%220007%22,%22questionCode%22:%220011%22,%22questionType%22:%222%22,%22pid%22:%22-1%22,%22answerCode%22:%220001%22,%22answerContext%22:%22%22%7D,%7B%22questionnaireId%22:%220007%22,%22questionCode%22:%220012%22,%22questionType%22:%223%22,%22pid%22:%22-1%22,%22answerCode%22:%22,0002%22,%22answerContext%22:%22%22%7D,%7B%22questionnaireId%22:%220007%22,%22questionCode%22:%220013%22,%22questionType%22:%222%22,%22pid%22:%22-1%22,%22answerCode%22:%220001%22,%22answerContext%22:%22%22%7D,%7B%22questionnaireId%22:%220007%22,%22questionCode%22:%220014%22,%22questionType%22:%222%22,%22pid%22:%22-1%22,%22answerCode%22:%220002%22,%22answerContext%22:%22%22%7D,%7B%22questionnaireId%22:%220007%22,%22questionCode%22:%220015%22,%22questionType%22:%223%22,%22pid%22:%22-1%22,%22answerCode%22:%22,0001,0003%22,%22answerContext%22:%22%22%7D,%7B%22questionnaireId%22:%220007%22,%22questionCode%22:%220016%22,%22questionType%22:%223%22,%22pid%22:%22-1%22,%22answerCode%22:%22,0001%22,%22answerContext%22:%22%22%7D,%7B%22questionnaireId%22:%220007%22,%22questionCode%22:%220017%22,%22questionType%22:%222%22,%22pid%22:%22-1%22,%22answerCode%22:%22001%22,%22answerContext%22:%22%22%7D%5D\"}");

    }


    public static String httpURLPOSTCase(String methodUrl,String body) {
        //String methodUrl = "http://xxx.xxx.xx.xx:8280/xx/adviserxx/1.0 ";
        System.out.println("开始回传答案调用");
        System.out.println("入参methodUrl："+methodUrl);
        System.out.println("入参body："+body);
        String resultStr = "";
        HttpURLConnection connection = null;
        OutputStream dataout = null;
        BufferedReader reader = null;
        String line = null;
        try {
            URL url = new URL(methodUrl);
            connection = (HttpURLConnection) url.openConnection();// 根据URL生成HttpURLConnection
            connection.setDoOutput(true);// 设置是否向connection输出，因为这个是post请求，参数要放在http正文内，因此需要设为true,默认情况下是false
            connection.setDoInput(true); // 设置是否从connection读入，默认情况下是true;
            connection.setRequestMethod("POST");// 设置请求方式为post,默认GET请求
            connection.setUseCaches(false);// post请求不能使用缓存设为false
            connection.setConnectTimeout(3000);// 连接主机的超时时间
            connection.setReadTimeout(3000);// 从主机读取数据的超时时间
            connection.setInstanceFollowRedirects(true);// 设置该HttpURLConnection实例是否自动执行重定向
            connection.setRequestProperty("connection", "Keep-Alive");// 连接复用
            connection.setRequestProperty("charset", "utf-8");
            connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            connection.connect();// 建立TCP连接,getOutputStream会隐含的进行connect,所以此处可以不要

            dataout = new DataOutputStream(connection.getOutputStream());// 创建输入输出流,用于往连接里面输出携带的参数
            //String body = "[{\"orderNo\":\"44921902\",\"adviser\":\"张怡筠\"}]";
            dataout.write(body.getBytes());
            dataout.flush();
            dataout.close();

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));// 发送http请求
                StringBuilder result = new StringBuilder();
                // 循环读取流
                while ((line = reader.readLine()) != null) {
                    result.append(line).append(System.getProperty("line.separator"));//
                }
                resultStr=result.toString();
                System.out.println(result.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            connection.disconnect();

        }
        return resultStr;
    }

    public static String httpsUrlConnectionPost(String params, String requestUrl)  {
        String result = null;
        try {
            trustAllHosts();
            URL serverUrl = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) serverUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type","text/xml; charset=utf-8");
            conn.setRequestProperty("Accept","*/*");
            //conn.setRequestProperty("SOAPAction", "QeuryGJAIDByIdNo");
            // 设置读取远程返回的数据时间：60000毫秒
            conn.setReadTimeout(60000);
            conn.setConnectTimeout(60000);
            conn.setInstanceFollowRedirects(false);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.connect();
            DataOutputStream out = new DataOutputStream(conn.getOutputStream());
            //out.writeBytes(params);
            out.write(params.getBytes("UTF-8"));
            out.flush();
            out.close();
            if (conn.getResponseCode() == 200) {
                result = getReturn(conn);
            } else {
                System.out.println("Return to Data is wrong");
            }
            Integer code = conn.getResponseCode();
            System.out.println(code.toString());
            result = getReturn(conn);
            System.out.println("httpUrlConnectionPost method end:"+result);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return result;
    }

    public static String getReturn(HttpURLConnection connection) throws IOException {
        StringBuffer buffer = new StringBuffer();
        try (InputStream inputStream = connection.getInputStream();
             InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
             BufferedReader bufferedReader = new BufferedReader(inputStreamReader);) {
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            String result = buffer.toString();
            return result;
        }
    }
    private static void trustAllHosts() {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[] {};
            }

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType){
            }
        } };

        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("SSL", "SunJSSE");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
                public boolean verify(String s, SSLSession sslsession) {
                    return true;
                }
            };
            HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
